function deepMerge(target, source) {
  if (typeof target !== 'object' || Array.isArray(target) || target === null)
    return target;
  if (typeof source !== 'object' || Array.isArray(source) || source === null)
    return source;

  for (let key in source) {
    if (
      source[key] instanceof Object &&
      target[key] instanceof Object &&
      !Array.isArray(source[key]) &&
      !Array.isArray(target[key])
    ) {
      target[key] = deepMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }

  return target;
}

const obj1 = {
  a: 1,
  b: {
    x: 10,
    y: 20,
  },
};

const obj2 = {
  b: {
    y: 30,
    z: 40,
  },
  c: 3,
};

const merged = deepMerge(obj1, obj2);
console.log(merged);
